import { login, getInfo, getUserInfoById } from '@/api/user'
import { resetRouter } from '@/router'
import { getToken, setToken, removeToken, setTimeStamp } from '@/utils/auth'
export default {
  namespaced: true,
  state: {
    // token: localStorage.getItem('vue-hr') || ''
    token: getToken() || '',
    userInfo: {} // 用户信息
  },
  mutations: {
    setToken(state, payload) {
      state.token = payload
      // localStorage.setItem('vue-hr', payload)
      setToken(payload)
    },
    delToken(state) {
      state.token = ''
      // localStorage.removeItem('vue-hr')
      removeToken()
    },
    // 存用户信息
    setUserInfo(state, payload) {
      state.userInfo = payload
    },
    // 删用户信息
    delUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    // 退出登录清空token // 清空路由
    logout(context) {
      context.commit('delToken')
      context.commit('delUserInfo')
      // 重置路由
      resetRouter()
    },
    // 获取用户信息存储到vuex中
    async userInfo(context) {
      try {
        const { data } = await getInfo()
        const photo = await getUserInfoById(data.data.userId)
        // console.log(data.data, 'photo')
        // console.log({ ...data.data, ...photo.data })
        context.commit('setUserInfo', { ...data.data, ...photo.data })
        return data.data.roles.menus
      } catch (error) {
        console.log(error)
      }
    },
    async userLogin(context, payload) {
      // 发ajax 登录 获取数据 存储到vuex
      const { data } = await login(payload)
      context.commit('setToken', data.data)
      // 调用存储获取token的时间戳
      setTimeStamp()
    }
  }
}

